import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入一级路由
import Detail from '@/views/Detail'
import Layout from '@/views/Layout'
import Login from '@/views/Login'
import Register from '@/views/Register'
// 导入二级路由

import Article from '@/views/Article'
import Collect from '@/views/Collect'
import Like from '@/views/Like'
import User from '@/views/User'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
  // 默认首页为 Layout
  { path: '/', redirect: '/layout' },
  { path: '/detail/:id', component: Detail },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/layout',
    component: Layout,
    redirect: '/article',
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 白名单
const arr = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 什么情况下可以正常跳转？ 1.有token 2，本身就是去登录页或者注册页
  if (getToken() || arr.includes(to.path)) {
    next() // 放行
  } else {
    next('/login')
  }
})

export default router
